package net.begincode.maiev.util;

import net.begincode.maiev.bean.MailAlarmMessage;
import net.begincode.maiev.common.MailConstant;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

import static org.jsoup.nodes.Document.OutputSettings.Syntax.html;

/**
 * Created by Stay on 2017/4/18  21:05.
 */
public class EmailUtils {

    public static void main(String[] args) {
        MailAlarmMessage message = new MailAlarmMessage();
        message.setMonitorName("test");
        message.setProjectName("test");
        message.setMailTitle("test");
        message.setMaxTime(1000L);
        sendEmail("532424981@qq.com", message);
    }

    public static void sendEmail(String receiveMailAccount, MailAlarmMessage alarmMessage) {
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", MailConstant.SEND_EMAIL_SMTP_HOST);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证

        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);                                 // 设置为debug模式, 可以查看详细的发送 log
        Transport transport = null;
        try {
            // 3. 创建一封邮件
            MimeMessage message = createMimeMessage(session, MailConstant.SEND_EMAIL_ACCOUNT, receiveMailAccount, alarmMessage);
            // 4. 根据 Session 获取邮件传输对象
            transport = session.getTransport();
            transport.connect(MailConstant.SEND_EMAIL_ACCOUNT, MailConstant.SEND_EMAIL_AUTHORIZATION_CODE);

            transport.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }

    }

    private static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, MailAlarmMessage alarmMessage) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(sendMail, alarmMessage.getMailSendName(), "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "UTF-8"));

        // 4. Subject: 邮件主题
        message.setSubject(alarmMessage.getMailTitle(), "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("用户您好,")
                .append(alarmMessage.getProjectName() + "  项目中的" + alarmMessage.getMonitorName() + "已经超时达到您所定好的阈值，")
                .append("最大超时时间为" + alarmMessage.getMaxTime() + "ms")
                .append("   请时刻关注该项目!!!");
        message.setContent(stringBuilder.toString(), "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }

}
